import {createRouter, createWebHashHistory} from 'vue-router'
import LogIn from '@/views/LogIn'
import LayOut from '@/views/LayOut'
import FileListHeader from '@/components/file/FileListHeader'
import Files from '@/views/file/Files'
import NotFound from '@/views/NotFound'
import Register from '@/views/Register'
import Tasks from '@/views/task/Tasks'
import store from '@/store'

const routes = [
    {
        path: '/login',
        name: 'login',
        meta: {
            noLogin: true
        },
        component: LogIn
    },
    {
        path: '/register',
        name: 'register',
        component: Register
    },
    {
        path: '/',
        name: 'LayOut',
        component: LayOut,
        children: [
            {
                path: '/files/:filePaths*',
                name: 'files',
                meta: {
                    menuIndex: '/files',
                    breadcrumb: (route) => {
                        const paths = route.params.filePaths || []
                        return ['首页', '我的资源', ...paths.filter((s) => Boolean(s))]
                    }
                },
                components: {
                    default: Files,
                    extra: FileListHeader
                }
            },
            {
                path: '/tasks',
                name: 'tasks',
                meta: {
                    menuIndex: '/tasks',
                    breadcrumb: ['首页', '管理任务']
                },
                component: Tasks,
            },
            {
                path: '/404',
                name: 'not_found',
                meta: {
                    menuIndex: '/404',
                    breadcrumb: ['首页', '404']
                },
                component: NotFound,
            },
            {
                path: '/:pathMatch(.*)*',
                redirect: {name: 'not_found'},
            },
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

router.beforeEach(async(to, from, next) => {
    if(to.path === '/login') {
        next()
    } else {
        if(!store.state.authToken) {
            next({name: 'login'})
        } else {
            next()
        }
    }
})

export default router
